package com.atguigu.tingshu.user.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.LastUserListenPlayVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import io.swagger.v3.core.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Autowired
	private StringRedisTemplate redisTemplate;

	@Autowired
	private KafkaService kafkaService;

	@Override
	public void updateListenProcess(UserListenProcessVo userListenProcessVo) {
		// 获取用户的ID
		Long userId = AuthContextHolder.getUserId();
		// 构建将要保存的集合名称,  位数是用 当前的 userId%100 获取的范围是 0-99
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		// 根据条件获取播放进度,
		UserListenProcess userListenProcess = mongoTemplate.findOne(Query.query(Criteria
				.where("userId").is(userId)
				.and("albumId").is(userListenProcessVo.getAlbumId())
				.and("trackId").is(userListenProcessVo.getTrackId())), UserListenProcess.class, collectionName);
		// 进度没有的话就添加
		if (Objects.isNull(userListenProcess)) {
			userListenProcess = new UserListenProcess();
			userListenProcess.setUserId(userId);
			userListenProcess.setAlbumId(userListenProcessVo.getAlbumId());
			userListenProcess.setTrackId(userListenProcessVo.getTrackId());
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			userListenProcess.setIsShow(1);
			userListenProcess.setCreateTime(new Date());
		} else {
			// 进度有的话就修改
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
		}
		userListenProcess.setUpdateTime(new Date());
		mongoTemplate.save(userListenProcess, collectionName);
		// 查询今天该用户有没有播放
		String trackPayRedisKey = RedisConstant.getTrackPayRedisKey(userListenProcess.getTrackId(), userId);
		boolean hasKey = Boolean.TRUE.equals(redisTemplate.hasKey(trackPayRedisKey));
		// 没有播放,第一次就算播放量
		if (!hasKey) {
			TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
			trackStatMqVo.setBusinessNo(UUID.randomUUID().toString().replaceAll("-", ""));
			trackStatMqVo.setAlbumId(userListenProcess.getAlbumId());
			trackStatMqVo.setTrackId(userListenProcess.getTrackId());
			trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
			trackStatMqVo.setCount(1);
			// 通知 service-album 微服务更新统计数据
			kafkaService.sendMsg(KafkaConstant.QUEUE_TRACK_STAT_UPDATE, JSON.toJSONString(trackStatMqVo));
			// redis 记录今日已经计算过了,记录到 redis
			redisTemplate.opsForValue().set(trackPayRedisKey, "1", 1, TimeUnit.DAYS);
		}

	}

	@Override
	public BigDecimal getTrackBreakSecond(Long trackId) {
		// 获取用户ID
		Long userId = AuthContextHolder.getUserId();
		// 构建将要保存的集合名称,  位数是用 当前的 userId%100 获取的范围是 0-99
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		// 获取进度
		UserListenProcess mongoTemplateOne = mongoTemplate.findOne(Query.query(Criteria
				.where("userId").is(userId)
				.and("trackId").is(trackId)), UserListenProcess.class, collectionName);
		// 有进度就返回进度,没进度就返回0
		return Objects.nonNull(mongoTemplateOne) ? mongoTemplateOne.getBreakSecond() : new BigDecimal("0");
	}

	@Override
	public LastUserListenPlayVo getLatelyTrack() {
		Long userId = AuthContextHolder.getUserId();
		LastUserListenPlayVo lastUserListenPlayVo;
		UserListenProcess mongoTemplateOne = mongoTemplate.findOne(Query
				.query(Criteria.where("userId").is(userId))
				.limit(1)
				.with(Sort.by(Sort.Order.desc("updateTime"))), UserListenProcess.class);
		if (Objects.isNull(mongoTemplateOne)) {
			lastUserListenPlayVo = LastUserListenPlayVo.builder().albumId(12L).trackId(592L).build();
		} else {
			lastUserListenPlayVo = LastUserListenPlayVo.builder().albumId(mongoTemplateOne.getAlbumId()).trackId(mongoTemplateOne.getTrackId()).build();
		}

		return lastUserListenPlayVo;
	}
}
